package hu.bme.mit.rifl.business.monitor;

import hu.bme.mit.rifl.business.base.WFElement;
import hu.bme.mit.rifl.business.shared.Coordinator;
import hu.bme.mit.rifl.datamodel.Order;

import java.util.Collection;

/**
 * A monitoring node which traces the finished work items, i.e. the Orders
 * already passed through the entire workflow. Checks the size of the
 * FinishedOrderQueue and compares it to the lastItemNumber property; if the
 * result is more than the one stored in the lastItemNumber, the queue is
 * getting polled and the lastItemNumber property is incremented.
 */
public class FinishedOrderMonitor extends WFElement {

	// stores the size of the FinishedOrderQueue last time it was polled
	private int lastItemNumber = 0;

	public FinishedOrderMonitor(Coordinator coordinator) {
		super(coordinator, "FinishedOrderMonitor");
		this.gui.setAutoSelected(true);
	}

	/**
	 * No actual business logic this time, since it's a diagnostical node, not a
	 * business one.
	 */
	@Override
	public void process() {
	}

	@Override
	public void run() {
		while (true) {
			try {
				if (lastItemNumber < coordinator.getFinishedQueue().size()) {
					gui.called();
					gui.log("\n### NEW FINISHED ORDER ###\n");

					while (!gui.isButtonClicked()) {
						Thread.sleep(100);
					}
					process();

					LogResult();
					lastItemNumber = coordinator.getFinishedQueue().size();
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
	}

	/**
	 * Overridden log method. The information is viewed on the console and in
	 * the monitoring window.
	 */
	@Override
	protected void LogResult() {
		gui.clearLog();
		String log = "";
		Collection<Order> orders = coordinator.getFinishedQueue();
		for (Order order : orders) {
			log = log + "\n";
			log = log + "Finished Order process. OrderID:" + order.getOrderID()
					+ ". State: " + order.getState() + ".";
		}

//		System.out.println(log);
		gui.log(log);
	}
}
